#!/bin/bash
set -euo pipefail

######################
# EasyTier 安装 + 开机自启 脚本 安装地址：bash -c "$(curl -fsSL https://gitee.com/junkoaao/junset/raw/master/pan.sh)"
######################

VPN_DIR="/vpn"
EASYTIER_URL="https://ghfast.top/https://github.com/EasyTier/EasyTier/releases/download/v2.4.5/easytier-linux-aarch64-v2.4.5.zip"
EASYTIER_ZIP="easytier-linux-aarch64-v2.4.5.zip"
EASYTIER_DIR="$VPN_DIR/easytier-linux-aarch64"
EASYTIER_CORE="$EASYTIER_DIR/easytier-core"
NETWORK_NAME="panjun"
NETWORK_SECRET="anhuang520"
PORT="tcp://public.easytier.cn:11010"
SUBNET="192.168.0.0/16"
LOG_FILE="/var/log/easytier-core.log"
SERVICE_FILE="/etc/systemd/system/easytier.service"

# 要求 root 权限执行
if [ "$(id -u)" -ne 0 ]; then
  echo "❌ 请以 root 或 sudo 执行此脚本"
  exit 1
fi

echo "====== EasyTier 安装 & 开机自启 脚本 ======"

# 安装依赖
echo "[*] 安装 unzip 和 curl ..."
apt update -y
apt install -y unzip curl || { echo "❌ 安装 unzip/curl 失败"; exit 1; }

# 下载与解压
mkdir -p "$VPN_DIR"
cd "$VPN_DIR"

if [ -f "$EASYTIER_ZIP" ]; then
  echo "[*] $EASYTIER_ZIP 已存在，跳过下载"
else
  echo "[*] 正在下载 EasyTier ..."
  curl -L --fail -o "$EASYTIER_ZIP" "$EASYTIER_URL" || { echo "❌ 下载失败"; exit 1; }
fi

if [ -d "$EASYTIER_DIR" ] && [ -x "$EASYTIER_CORE" ]; then
  echo "[*] 已解压且有执行权限，跳过解压"
else
  echo "[*] 解压 $EASYTIER_ZIP ..."
  unzip -o "$EASYTIER_ZIP"
  chmod +x "$EASYTIER_CORE"
fi

# 准备日志文件
mkdir -p "$(dirname "$LOG_FILE")"
touch "$LOG_FILE"
chmod 644 "$LOG_FILE"

# 写 systemd 服务文件
echo "[*] 写入 systemd 服务：$SERVICE_FILE"
cat > "$SERVICE_FILE" <<EOF
[Unit]
Description=EasyTier VPN Service
After=network.target

[Service]
Type=simple
ExecStart=$EASYTIER_CORE -d --network-name $NETWORK_NAME --network-secret $NETWORK_SECRET -p $PORT -n $SUBNET
WorkingDirectory=$VPN_DIR
StandardOutput=append:$LOG_FILE
StandardError=append:$LOG_FILE
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

# 启动与设置自启
echo "[*] 启用并启动 easytier 服务"
systemctl daemon-reload
systemctl enable easytier
systemctl restart easytier

# 检测状态
sleep 2
if systemctl is-active --quiet easytier; then
  echo "✅ easytier 服务已启动"
  echo "查看日志：journalctl -u easytier -f"
else
  echo "❌ 服务启动失败，请检查日志：$LOG_FILE"
  exit 1
fi

echo "====== 安装完成 ======"
